package com.example.myapplication.ui.home

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.provider.OpenableColumns
import android.util.Log
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.GridLayoutManager
import com.example.myapplication.databinding.ActivityPicPhotoBinding
import com.example.myapplication.picUtils.ImagePicker
import com.example.myapplication.picUtils.ImagePickerActivity
import com.example.myapplication.picUtils.ImagePickerCallback
import java.io.File

class PicPhotoActivity:AppCompatActivity(), ImagePickerCallback {
    val REQUEST_CODE_PICK_IMAGE = 1001

    private lateinit var imagePicker: ImagePicker // 声明为成员变量
    private val binding: ActivityPicPhotoBinding by lazy {
        ActivityPicPhotoBinding.inflate(layoutInflater)
    }

    val pickMultipleMedia =
        registerForActivityResult(ActivityResultContracts.PickMultipleVisualMedia(5)) { uris ->
            // Callback is invoked after the user selects media items or closes the
            // photo picker.
            if (uris.isNotEmpty()) {

                Log.d("PhotoPicker", "Number of items selected: ${uris.size}")
                Log.d("PhotoPicker", "${uris.last().path}")


            } else {
                Log.d("PhotoPicker", "No media selected")
            }
        }

    // 定义权限请求启动器
    private val requestMultiplePermissionsLauncher = registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) { permissions ->
        permissions.entries.forEach { entry ->
            val permissionName = entry.key
            val isGranted = entry.value
            if (isGranted) {
                // 单个权限已授予
                pickMultipleMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageAndVideo))
            } else {
                // 单个权限被拒绝
            }
        }
    }
    private lateinit var picAdapter: PicAdapter
    private val selectedPicItems = mutableListOf<PicItem>() // 用于跟踪选中的图片

   override fun onCreate(savedInstanceState: Bundle?){
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
       // 此时 Activity 状态还未到 STARTED，符合注册要求
       imagePicker = ImagePicker.with(this, this)
           .allowMultiple(true, 3)
           .enableCompression(true)
           .compressionQuality(75)
           .compressionDimensions(800,800)
           // .targetDirectory(File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "Compressed")) // 如果需要自定义目录
           .build() // 只构建实例，不立即启动选择器
       binding.button.setOnClickListener {
//           requestPermission()
//           imagePicker.launchPicker() // 开始选择

           ImagePickerActivity.start(
               this,
               REQUEST_CODE_PICK_IMAGE,
               maxCount = 5, // 最多选5张
               enableCompress = true // 启用Luban压缩
           )
       }


       picAdapter = PicAdapter { clickedPicItem ->
           // 处理项目点击事件
           // 例如，切换选中状态
           val currentList = picAdapter.currentList.toMutableList()
           val index = currentList.indexOfFirst { it.id == clickedPicItem.id }
           if (index != -1) {
               val itemToUpdate = currentList[index].copy(isSelected = !currentList[index].isSelected)
               currentList[index] = itemToUpdate
               picAdapter.submitList(currentList) // 提交更新后的列表

               // 或者使用 adapter 提供的辅助方法
               // picAdapter.toggleSelection(clickedPicItem)

               // 更新您自己维护的选中列表
               if (itemToUpdate.isSelected) {
                   if (!selectedPicItems.any { it.id == itemToUpdate.id }) {
                       selectedPicItems.add(itemToUpdate)
                   }
               } else {
                   selectedPicItems.removeAll { it.id == itemToUpdate.id }
               }
               Log.d("PicSelection", "Clicked: ${clickedPicItem.uri}, Selected: ${itemToUpdate.isSelected}")
               Log.d("PicSelection", "Total selected: ${picAdapter.getSelectedItems().size}")
           }
       }

       binding.recyclerView.layoutManager = GridLayoutManager(this, 3) // 例如使用网格布局
       binding.recyclerView.adapter = picAdapter

    }

    private fun requestPermission() {
        // 使用方式
        requestMultiplePermissionsLauncher.launch(
            arrayOf(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA,
                Manifest.permission.READ_MEDIA_IMAGES
            )
        )
    }

    // 从URI获取文件名
    fun getFileNameFromUri(uri: Uri): String {
        var fileName = "upload_file"
        val cursor = contentResolver.query(uri, null, null, null, null)
        cursor?.use {
            if (it.moveToFirst()) {
                val displayNameIndex = it.getColumnIndex(OpenableColumns.DISPLAY_NAME)
                if (displayNameIndex != -1) {
                    fileName = it.getString(displayNameIndex)
                }
            }
        }
        return fileName
    }

    override fun onImagesSelected(originalUris: List<Uri>, compressedFiles: List<File>?) {
        val picItems = originalUris.map { uri ->
            // 检查这个 URI 是否已经在之前选中的列表中
            val previouslySelectedItem = selectedPicItems.find { it.uri == uri }
            PicItem(uri, isSelected = previouslySelectedItem?.isSelected ?: false)
        }
        picAdapter.submitList(picItems)
    }

    override fun onError(exception: Exception) {
        TODO("Not yet implemented")
    }

    override fun onPermissionDenied(deniedPermissions: List<String>) {
        TODO("Not yet implemented")
    }

    @Deprecated("Deprecated in Java")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE_PICK_IMAGE && resultCode == Activity.RESULT_OK) {
            data?.let {
                val originalUris: ArrayList<Uri>? =
                    it.getParcelableArrayListExtra(ImagePickerActivity.RESULT_PICKED_IMAGES)
                val compressedPaths: ArrayList<String>? =
                    it.getStringArrayListExtra(ImagePickerActivity.RESULT_COMPRESSED_IMAGES)

                originalUris?.forEach { uri ->
                    Log.d("YourActivity", "Original URI: $uri")
                    // 使用 Coil 加载显示原始图片 uri
                }


                compressedPaths?.forEach { path ->
                    Log.d("YourActivity", "Compressed Path: $path")
                    // 使用 Coil 加载显示压缩后的图片 File(path)

                }

                if (originalUris.isNullOrEmpty()) {
                    Log.d("YourActivity", "No images selected or returned.")
                }

                val picItems = originalUris?.map { uri ->
                    // 检查这个 URI 是否已经在之前选中的列表中
                    val previouslySelectedItem = selectedPicItems.find { it.uri == uri }
                    PicItem(uri, isSelected = previouslySelectedItem?.isSelected ?: false)
                }
                picAdapter.submitList(picItems)
            }
        }
    }
}
